#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图片垂直合并工具
将用户选择的多张图片垂直合并成一张图片
"""

import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image


def select_images():
    """
    使用文件对话框选择多张图片
    """
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    
    file_paths = filedialog.askopenfilenames(
        title="选择要合并的图片",
        filetypes=[
            ("图片文件", "*.jpg *.jpeg *.png *.bmp *.gif *.tiff"),
            ("所有文件", "*.*")
        ]
    )
    
    return list(file_paths)


def save_image_dialog():
    """
    使用文件对话框选择保存位置
    """
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    
    file_path = filedialog.asksaveasfilename(
        title="保存合并后的图片",
        defaultextension=".png",
        filetypes=[
            ("PNG图片", "*.png"),
            ("JPEG图片", "*.jpg"),
            ("所有文件", "*.*")
        ]
    )
    
    return file_path


def merge_images_vertically(image_paths, output_path):
    """
    将多张图片垂直合并成一张图片
    
    参数:
        image_paths: 图片路径列表
        output_path: 输出图片路径
    """
    if not image_paths:
        print("错误：没有选择图片")
        return False
    
    try:
        # 打开所有图片
        images = []
        max_width = 0
        total_height = 0
        
        print(f"正在处理 {len(image_paths)} 张图片...")
        
        for img_path in image_paths:
            try:
                img = Image.open(img_path)
                images.append(img)
                
                # 计算最大宽度和总高度
                width, height = img.size
                max_width = max(max_width, width)
                total_height += height
                
                print(f"已加载: {os.path.basename(img_path)} ({width}x{height})")
            except Exception as e:
                print(f"无法打开图片 {img_path}: {e}")
                return False
        
        # 创建新图片
        merged_image = Image.new('RGB', (max_width, total_height), (255, 255, 255))
        
        # 垂直合并图片
        y_offset = 0
        for i, img in enumerate(images):
            # 如果图片宽度小于最大宽度，居中放置
            width, height = img.size
            x_offset = (max_width - width) // 2
            
            # 将图片粘贴到新图片上
            merged_image.paste(img, (x_offset, y_offset))
            y_offset += height
            
            print(f"已合并: {os.path.basename(image_paths[i])}")
        
        # 保存合并后的图片
        merged_image.save(output_path)
        print(f"合并完成！图片已保存到: {output_path}")
        
        # 关闭所有图片
        for img in images:
            img.close()
            
        return True
    
    except Exception as e:
        print(f"合并图片时出错: {e}")
        return False


def main():
    """
    主函数
    """
    print("图片垂直合并工具")
    print("=" * 30)
    
    # 选择要合并的图片
    image_paths = select_images()
    
    if not image_paths:
        print("没有选择图片，程序退出。")
        return
    
    # 选择保存位置
    output_path = save_image_dialog()
    
    if not output_path:
        print("没有选择保存位置，程序退出。")
        return
    
    # 合并图片
    success = merge_images_vertically(image_paths, output_path)
    
    if success:
        messagebox.showinfo("成功", f"图片已成功合并并保存到:\n{output_path}")
    else:
        messagebox.showerror("错误", "合并图片时出错，请检查图片格式是否正确。")


if __name__ == "__main__":
    main()